package io.github.wppli.trigger.job;

import io.github.wppli.domain.posts.model.valobj.PostsLikeCountVO;
import io.github.wppli.domain.posts.model.valobj.UserPostsBehaviorType;
import io.github.wppli.domain.posts.service.PostsCountService;
import io.github.wppli.domain.recommond.repository.IUserPostsBehaviorRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author li--jiaqiang 2025−03−11
 */
@Slf4j
@Component
@AllArgsConstructor
public class PostsCountTaskJob {

    private final PostsCountService postsCountService;
    private final IUserPostsBehaviorRepository userPostsBehaviorRepository;

    // 10s 执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void exec() {
        try {
            PostsLikeCountVO postsLikeCountVO = postsCountService.takeLikeQueueValue();
            if (null == postsLikeCountVO) return;
            Long userId = postsLikeCountVO.getUserId();
            Long postId = postsLikeCountVO.getPostId();
            UserPostsBehaviorType userPostsBehaviorType = postsLikeCountVO.getUserPostsBehaviorType();
            log.info("定时任务，更新帖子点赞数目-插入用户点赞行为 postsId:{} userId:{} adjustCount:{}",
                    postId, userId, postsLikeCountVO.getAdjustCount());
            postsCountService.updatePostsLikeCount(postId, postsLikeCountVO.getAdjustCount());
            // 插入一条关注记录
            int status = postsLikeCountVO.getAdjustCount() == 1 ? 1 : 0;
            postsCountService.updateOrInsertLike(postsLikeCountVO.getPostId(),postsLikeCountVO.getUserId(), status);
            // 插入用户对Posts得行为
            userPostsBehaviorRepository.save(userId, postId, userPostsBehaviorType);
        } catch (Exception e) {
            log.error("定时任务，更新帖子点赞数目-插入用户点赞行为 失败", e);
        }
    }
}